from rest_framework import serializers
from users.models import User


class UserSerializer(serializers.ModelSerializer):
    """ 用户 模型类序列化器"""

    class Meta:
        model = User
        fields = ("id", "username", "mobile", "email", "password")
        extra_kwargs = {
            "username": {"max_length": 20, "min_length": 5},
            "password": {"max_length": 20, "min_length": 8, "write_only": True},    # 只参与反序列化
        }

    def create(self, validated_data):
        # 重写模型类序列化器的create方法，使用create_user来实现新建User对象密码加密
        validated_data["is_staff"] = True   # 默认新建的是后台运营用户
        user = User.objects.create_user(**validated_data)
        return user
